/*
 * @Description: 子应用
 * @Author: Caroline
 * @Date: 2024-02-24 23:48:20
 * @LastEditTime: 2024-02-27 22:08:45
 * @LastEditors: Caroline
 * @FilePath: \ronghe-web\src\hooks\useApplication.ts
 */

import { ElMessage } from "element-plus";
import { CacheToken } from "@/constants/cacheKey";
import { useAppStore } from "@/store";
import { getCache } from "@/utils/cache";
import { BUY_STATUS } from "@/views/biz/application/type";
import { APPLICATION } from "@/views/biz/application/type";

export default () => {
  const store = useAppStore();

  //   跳转子应用
  const goToApplication = (
    item: { id: string; loginUrl: string; status: number },
    params?: { type?: string; companyId?: string }
  ) => {
    if (item.status + "" === BUY_STATUS.NOT_PURCHASED + "") {
      ElMessage.warning("你还没购买该应用哦~");
      return;
    }
    const { password, unncryptPassword } = getCache(CacheToken, { isSessionStorage: true }) || {};
    const transferPageParam: {
      username: string;
      password: string;
      companyId?: string;
    } = {
      username: store.state.user.username,
      password
    };
    if (item.id === APPLICATION.CLEAN) {
      transferPageParam.companyId = params?.companyId;
    } else if (item.id === APPLICATION.RIVER) {
      transferPageParam.password = unncryptPassword;
    }
    let querys = encodeURIComponent(JSON.stringify(transferPageParam));
    if (item.loginUrl.includes("=") && item.loginUrl.includes("?")) {
      querys = `&transferPageParam=${querys}`;
    } else {
      querys = `?transferPageParam=${querys}`;
    }
    window.open(`${item.loginUrl}${querys}`, params?.type || "_blank");
  };

  return {
    goToApplication
  };
};
